import $C from './config.js';
import $store from '@/store/index.js';

export const requestClound = (cloudFnName, operation, data = {}, ext = {}) => {
	return new Promise((resolve, reject) => {
		if (ext.showLoading !== false) {
			uni.showLoading()
		}
		uniCloud.callFunction({
			name: cloudFnName,
			data: {
				operation,
				data
			}
		}).then(res => {
			if (ext.showLoading !== false) {
				uni.hideLoading()
			}
			resolve(res.result.data);
		}).catch((err) => {
			if (ext.showLoading !== false) {
				uni.hideLoading()
			}
			reject(err);
		})
	})
}

export default {
	// 全局配置
	common: {
		baseUrl:$C.baseUrl,
		header: {
			'Content-Type': 'application/json;charset=UTF-8'
		},
		data: {},
		method: 'GET',
		dataType: 'json',
		token: false
	},
	// 请求 返回promise
	request(options = {}) {
		let common = this.common;
		// 组织参数
		options.url = common.baseUrl + options.url;
		options.header = options.header || common.header;
		options.data = options.data || common.data;
		options.method = options.method || common.method;
		options.dataType = options.dataType || common.dataType;
		options.token = options.token === true ?  true : common.token
		
		// token
		if (options.token) {
			let token = uni.getStorageSync('token')
			// 二次验证
			if (!token) {
				return uni.reLaunch({
					url: '/pages/login/login',
				});
			}
			// options.header.token = token;
			options.header.Authorization = token; // Bearer
		}
		
		// 请求
		return new Promise((res, rej) => {
			// uni.showLoading({title: '加载中...', mask: true});
			uni.request({
				...options,
				success(result) {
					// 停止页面下拉刷新
					uni.stopPullDownRefresh();
					// 隐藏加载动画
					uni.hideLoading();
					let {statusCode, data} = result;
					// 返回原始数据
					if (options.native) return res(result);
					// 服务端失败
					if (statusCode !== 200 || data.code !== 200) {
						if (options.toast !== false) {
							uni.showToast({ title: data.msg || '服务端失败', icon: 'none' });
						}
						// token不合法，直接退出登录
						if (data.code === 401) {
							$store.commit('logout')
						}
						return rej(data)
					}
					// 成功
					res(data)
				},
				fail({errMsg}) {
					// 停止页面下拉刷新
					uni.stopPullDownRefresh();
					// 隐藏加载动画
					uni.hideLoading();
					uni.showToast({ title: errMsg || '请求失败', icon: 'none' });
					return rej()
				}
			});
		})
	},
	// get请求
	get(url, data = {}, options = {}) {
		options.url = url;
		options.data = data;
		options.method = 'GET';
		return this.request(options)
	},
	// post请求
	post(url, data = {}, options = {}) {
		options.url = url;
		options.data = data;
		options.method = 'POST';
		return this.request(options)
	},
	// delete请求
	del(url, data = {}, options = {}) {
		options.url = url;
		options.data = data;
		options.method = 'DELETE';
		return this.request(options)
	}
}
